const debug = require('debug')('node_arch:autoupdate');
const util = require('util');

async function update(dataSource) {
  dataSource.setMaxListeners(30);
  const isActual = await util.promisify(dataSource.isActual.bind(dataSource))();
  if (isActual) {
    debug(`${dataSource.name} has no changes`);
    return null;
  }
  debug(`${dataSource.name} is updating...`);
  return util.promisify(dataSource.autoupdate.bind(dataSource))()
    .then(() => {
      debug(`${dataSource.name} has updated successfully`);
    })
    .catch((error) => {
      console.log(error);
    });
}

module.exports = function setup() {
  debug('-----begin-----');
  return function (dataSources) {
    dataSources = dataSources || [];
    return Promise
      .all(dataSources.map(dataSource => update(dataSource)))
      .then(() => {
        debug('-----end-----');
      });
  };
};
